package com.ds.infrastructure.hyperspace.container.internal.operator;

import io.netty.handler.codec.http.QueryStringDecoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * usage eg:
 *  [HTTP_QUERY_VALUE, 'g|groupID']
 * @author  Weishaoying
 */
public class HttpQueryValueOperator extends AbstractOperator {

    private static final int AGRS_LENGTH = 1;

    @Override
    public String compute(String inputValue, String[] args) {
        if (StringUtils.isEmpty(inputValue) || args == null) {
            return null;
        }
        Map<String, List<String>> parameters = new QueryStringDecoder(inputValue).parameters();
        if (parameters.isEmpty()) {
            return null;
        }
        for (String tempQueryName : args) {
            List<String> queryValueList = parameters.get(tempQueryName);
            if (!CollectionUtils.isEmpty(queryValueList)) {
                return queryValueList.get(0);
            }
        }
        return null;
    }

    @Override
    public String getOperatorName() {
        return "HTTP_QUERY_VALUE";
    }

    @Override
    public int getOperatorArgsLength() {
        return AGRS_LENGTH;
    }
}
